﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cheems.Model.DataStructures
{
    /// <summary>
    /// [数据结构]固定长度List
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class FixedSizeList<T> : List<T>
    {
        private int _maxLength;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="maxLength">List最大长度</param>
        /// <exception cref="ArgumentException"></exception>
        public FixedSizeList(int maxLength)
        {
            if (maxLength <= 0)
            {
                throw new ArgumentException("最大长度必须大于0", nameof(maxLength));
            }

            _maxLength = maxLength;
        }

        /// <summary>
        /// 添加一条数据
        /// </summary>
        /// <param name="item"></param>
        public new void Add(T item)
        {
            base.Add(item);

            // 如果长度超过最大长度，移除最前面的元素
            EnsureSize();
        }

        /// <summary>
        /// 添加多条数据
        /// </summary>
        /// <param name="collection"></param>
        public new void AddRange(IEnumerable<T> collection)
        {
            foreach (var item in collection)
            {
                Add(item);
            }
        }

        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="index">插入位置</param>
        /// <param name="item">插入的数据</param>
        public new void Insert(int index, T item)
        {
            base.Insert(index, item);

            // 确保长度不超过最大长度
            EnsureSize();
        }

        /// <summary>
        /// 插入多条数据
        /// </summary>
        /// <param name="index">插入位置</param>
        /// <param name="collection">插入的数据集合</param>
        public new void InsertRange(int index, IEnumerable<T> collection)
        {
            base.InsertRange(index, collection);

            // 确保长度不超过最大长度
            EnsureSize();
        }

        /// <summary>
        /// 确保列表大小不超过最大长度
        /// </summary>
        private void EnsureSize()
        {
            while (Count > _maxLength)
            {
                RemoveAt(0);
            }
        }
    }

}
